package breeze.pixel.weather.aboutapp.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import breeze.pixel.weather.App;
import breeze.pixel.weather.BaseView;
import breeze.pixel.weather.R;
import breeze.pixel.weather.activity.DonateActivity;
import breeze.pixel.weather.apps_util.utils.Alipay;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.MDialog;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.apps_util.utils.appsettings.SettingsStaticData;
import breeze.pixel.weather.apps_util.views.WebActivity;
import breeze.pixel.weather.apps_util.views.mtextview.MTextView;
import breeze.pixel.weather.apps_util.views.mtoolbar.MToolbar;
import brz.breeze.app_utils.BAppUpdate;
import brz.breeze.app_utils.BAppUtils;
import brz.breeze.web_utils.BWebUtils;

public class AboutView extends BaseView implements IAboutView {

    private ProgressDialog updateProgressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);
        init();
        initData();
    }

    @Override
    public void init() {
        MToolbar toolbar = find(R.id.about_toolbar);
        toolbar.setNavigation(R.mipmap.icon_back, v -> finish());
    }

    @Override
    public void initData() {
        updateProgressDialog = new ProgressDialog(this);
        updateProgressDialog.setTitle("提示");
        updateProgressDialog.setCancelable(false);
        updateProgressDialog.setMessage("正在下载中...");
        MTextView version = find(R.id.about_version_codes);
        version.setText(String.format("V%s", AppToolUtil.getVerName(this)));
    }

    private void downloadAPK(String link) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
        startActivity(intent);
    }

    public void checkNewVer(View view) {
        BAppUpdate.setOnUpdateListener(this, AppSettings._UPDATE_APP_URI, new BAppUpdate.BAppUpdateListener() {
            @Override
            public void haveNewVersion(BAppUpdate.BUpdateMode bUpdateMode) {
                MDialog mDialog = new MDialog(AboutView.this);
                mDialog.setTitle("发现新版本");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(BAppUtils.getAppVersionName(App.getContext())).append("->").append(bUpdateMode.getAppVersionName());
                mDialog.setSubTitle(stringBuilder);
                mDialog.setMessage(bUpdateMode.getUpdateContent());
                mDialog.setPositiveButton("立即更新", () -> {
                    String link = bUpdateMode.getDownLink();
                    updateProgressDialog.show();
                    BWebUtils.downloadFile(link, AppToolUtil.getDownloadAPKPath(AboutView.this), new BWebUtils.WebDownloadListener() {
                        @Override
                        public void onProgress(int i) {

                        }

                        @Override
                        public void onSuccess(File file) {
                            toast("下载完成");
                            runOnUiThread(() -> {
                                updateProgressDialog.dismiss();
                                AppToolUtil.installAPK(AppToolUtil.getDownloadAPKPath(AboutView.this).getAbsolutePath(), AboutView.this);
                            });
                        }

                        @Override
                        public void onError(Exception e) {
                            runOnUiThread(() -> {
                                updateProgressDialog.dismiss();
                                toast("下载失败[" + e.toString() + "]");
                            });
                        }
                    });
                });
                mDialog.setNavigateBotton("忽略该版本", () -> sets.setIgnoreVersion(bUpdateMode.getAppVersion()));
                mDialog.setNegativeBotton("稍后更新", null);
                mDialog.show();
            }

            @Override
            public void noNewVersion() {
                toast("当前已经是最新版本啦！");
            }

            @Override
            public void onError(Exception e) {
                toast("检测更新失败:" + e.toString());
            }
        });
    }


    @Override
    public void clickAnim(View view) {
        ScaleAnimation animation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(300);
        animation.setFillAfter(false);
        view.startAnimation(animation);
    }

    @Override
    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    public void joinQQ(View view) {
        if (!joinQQGroup("lepIXINtLxsva0DmS0JXS7ogRmEaNc0E")) {
            toast("未安装手Q或安装的版本不支持");
        }
    }

    public void mianzeshengming(View view) {
        WebActivity.startActivity(this, SettingsStaticData._API_HOST + "/pixelweather/Privacy.html");
    }

    public void normal_problem(View view) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://sharechain.qq.com/80f97d96eab357a11f2cd1d3df10fc3c"));
        startActivity(intent);
    }

    public void pay_money(View view) {
        Intent intent = new Intent(this, DonateActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void resfrom(View view) {
        WebActivity.startActivity(this, SettingsStaticData._API_HOST + "/pixelweather/UserAgreement.html");
    }

    private void donate() {
        MDialog mDialog = new MDialog(this);
        mDialog.setTitle("捐赠软件");
        mDialog.setMessage("迫于生计推出此功能，由于BMOB的不稳定性，因此我自费开通了虚拟主机以作后台，但每个月都需支付一定成本，因此希望各位理解支持，各位的捐赠可以帮助我更好的更新软件，更好的为大家服务！\n感谢你们的支持。");
        mDialog.setPositiveButton("支付宝", () -> {
            if (Alipay.hasInstalledAlipayClient(AboutView.this)) {
                Alipay.startAlipayClient(AboutView.this, "fkx15110m5gwyphk8do2k16");
            } else {
                toast("未检测到支付宝APP");
            }
        });
        mDialog.setNegativeBotton("微信", () -> {
            try {
                InputStream inputStream = getAssets().open("wx/wechat_pay.png");
                Bitmap      bitmap      = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                AppToolUtil.insertPicture(this, bitmap);
                toast("微信收款码已保存到手机，感谢支持");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        mDialog.setNavigateBotton("点错了", null);
        mDialog.show();
    }
}